﻿using RabbitMQ.Client;
using Server;
using System;
using System.Text;

namespace WorkProducer
{
    class Program
    {
        static void Main(string[] args)
        {
            //https://www.rabbitmq.com/getstarted.html
            Console.WriteLine("工作队列");
            var msg = "";
            do
            {
                Console.WriteLine("输入你要发送的消息：");
                msg = Console.ReadLine(); ;
                WorkProducer.SendQueueMsg(msg);

            } while (msg.ToLower() != "out");
            // WorkProducer.SendQueueMsg("测试");

        }
    }


  public  class WorkProducer
    {
        private static readonly ConnectionFactory rabbitMqFactory = CommonConnectionFactory.rabbitMqFactory;

        public static void SendQueueMsg(string msg = "你你你")
        {


            string ExchangeName = "交换机";
            string QueueName = "工作队列";
            using (IConnection conn = rabbitMqFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    ////事务模式非常消耗性能， 使得RabbitMQ的吞吐量降低250倍，不再建议使用，可用发布者确认模式
                    //channel.TxSelect(); // 声明事务
                    try
                    {
                        //交换机名称，交换机类型，(durable)是否持久化，(autoDelete)是否自动删除
                        channel.ExchangeDeclare(ExchangeName, ExchangeType.Direct, durable: true, autoDelete: false, arguments: null);

                        channel.QueueDeclare(QueueName, durable: true, autoDelete: false, exclusive: false, arguments: null);
                        channel.QueueBind(QueueName, ExchangeName, routingKey: "工作模式");

                        var props = channel.CreateBasicProperties();
                        props.Persistent = true;


                        for (int i = 0; i < 30; i++)
                        {
                            var msgBody = Encoding.UTF8.GetBytes($@"-{msg}{i.ToString()}-");
                            channel.BasicPublish(exchange: ExchangeName, routingKey: "工作模式", basicProperties: props, body: msgBody);
                        }
                      //  channel.TxCommit();

                    }
                    catch (Exception e)
                    {
                        //事务模式非常消耗性能， 使得RabbitMQ的吞吐量降低250倍，不再建议使用，可用发布者确认模式
                       // channel.TxRollback();
                    }
                    finally
                    {
                        channel.Close();
                        conn.Close();
                    }
                }
            }
        }
    }
}
